
const sha1 = require('sha1');
const getRawBody = require('raw-body')
const util = require('./util')

module.exports = (config,reply) => {
    return async (ctx, next) => {
        const { signature, timestamp, nonce, echostr } = ctx.query;
        //token 是config wechat中的 token 
        const token = config.token;
        let str = [token, timestamp, nonce].sort().join('');
        //对str 进行加密 sha1
        const sha = sha1(str);

        if (ctx.method === 'GET') {
            if (sha === signature) {
                ctx.body = echostr;
            } else {
                ctx.body = 'Failed';
            }
        } else if (ctx.method === 'POST') {
            if (sha != signature) {
                return (ctx.body = 'Failed')
            }

            //自动回复
            const data = await getRawBody(ctx.req, {
                length: ctx.length,
                limit: '1mb',
                encoding: ctx.charset
            })

            const content = await util.parseXML(data);
            const message = util.formatMessage(content.xml);
            //动态去改变回复的消息
            ctx.automatic_answer = message;
            await reply.apply(ctx,[ctx,next])
            //使用模板字符串进行数据的处理
            const replyBody = ctx.body;
            const msg = ctx.automatic_answer;
            const xml = util.templateXml(replyBody,msg)

            ctx.status = 200;
            ctx.type = 'application/xml';
            ctx.body = xml;


        }

    }

}
















